package com.baipiao.permission.backend.config.security;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.baipiao.permission.backend.entity.response.Res;
import com.baipiao.permission.backend.entity.response.ResStatusEnum;

import java.io.IOException;

/**
 * @Description: 匿名用户访问无权限资源时的异常
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException {
        String res = JSONObject.toJSONString(Res.fail(ResStatusEnum.auth_fail));
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);// 401，未登录
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(res);
    }
}
